import paramiko
from django.conf import settings
import os
from .models import ServerModel
import csv
import pandas as pd
from concurrent.futures import ThreadPoolExecutor
import threading





class SSHClientPool:
    def __init__(self):
        self.pool = {}
        self.lock = threading.Lock()  # 用于确保线程安全

    def get_ssh_client(self, ip_addr, user, pwd):
        with self.lock:  # 确保线程安全
            if (ip_addr, user) not in self.pool or self.pool[(ip_addr, user)].get_transport().is_active is False:
                ssh_client = paramiko.SSHClient()
                ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh_client.connect(hostname=ip_addr, username=user, password=pwd)
                self.pool[(ip_addr, user)] = ssh_client
            return self.pool[(ip_addr, user)]

    def close_all_connections(self):
        with self.lock:
            for (ip_addr, user), ssh_client in list(self.pool.items()):
                ssh_client.close()
                del self.pool[(ip_addr, user)]

class SSHClient:
    def __init__(self):
        self.file_path = os.path.join(settings.BASE_DIR, 'csrec', 'webs.csv')
        self.ssh_pool = SSHClientPool()

    def fetch_cpu_usage(self, server_info):
        ip_addr, user, pwd = server_info
        ssh = self.ssh_pool.get_ssh_client(ip_addr, user, pwd)
        try:
            stdin, stdout, stderr = ssh.exec_command("top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'")
            result_usage = stdout.read().decode('utf-8').strip()
            if result_usage:
                cpu_usage = float(result_usage)
                return (ip_addr, cpu_usage)
            else:
                return (ip_addr, None)
        except Exception as e:
            print(f"Error fetching CPU usage from {ip_addr}: {e}")
            return (ip_addr, None)

    def get_cpu_info(self):
        try:
            data = pd.read_csv(self.file_path)
            ip = data['ip']
            username = data['username']
            password = data['password']

            with ThreadPoolExecutor(max_workers=3) as executor:
                futures = [executor.submit(self.fetch_cpu_usage, (ip_addr, user, pwd))
                            for ip_addr, user, pwd in zip(ip, username, password)]
                results = [future.result() for future in futures]

            x_list, y_list = zip(*[(ip, cpu_usage) for ip, cpu_usage in results if cpu_usage is not None])
            return list(x_list), list(y_list)
        finally:
            self.ssh_pool.close_all_connections()
            print("所有连接已关闭")


    def add_data(self):
        data = ServerModel.objects.all()
        data_list = []
        for i in data:
            data_dict = {
                'ip':i.ip,
                'username':i.username,
                'password':i.password
            }
            data_list.append(data_dict)



        with open(self.file_path, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(['ip', 'username', 'password'])
            for row in data_list:
                writer.writerow([row['ip'], row['username'],row['password']])
            csvfile.close()

        return data_list






ssh=SSHClient()